<template>
  <div class="enhanced-software-card" :class="{ 'selected': isSelected, 'loading': loading }">
    <!-- 软件图标和状态 -->
    <div class="card-header">
      <div class="software-icon">
        <el-image
          :src="software.iconUrl || defaultIcon"
          :alt="software.displayName"
          fit="cover"
          lazy
        >
          <template #error>
            <div class="image-slot">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
        
        <!-- 状态标志 -->
        <div class="status-badges">
          <el-tag v-if="software.status === 'NEW'" type="success" size="small">新品</el-tag>
          <el-tag v-if="software.rating >= 4.5" type="warning" size="small">推荐</el-tag>
          <el-tag v-if="isPopular" type="danger" size="small">热门</el-tag>
        </div>
      </div>

      <!-- 选择框 -->
      <div class="selection-box">
        <el-checkbox
          :model-value="isSelected"
          @change="handleSelectionChange"
          :disabled="loading"
          size="large"
        />
      </div>
    </div>

    <!-- 软件信息 -->
    <div class="card-body">
      <div class="software-title">
        <h3 class="name" :title="software.displayName">{{ software.displayName }}</h3>
        <div class="category-tag">
          <el-tag size="small" type="info">{{ software.category }}</el-tag>
        </div>
      </div>

      <div class="software-meta">
        <!-- 评分 -->
        <div class="rating" v-if="software.rating">
          <el-rate
            :model-value="software.rating"
            disabled
            show-score
            text-color="#ff9900"
            score-template="{value}"
            size="small"
          />
        </div>

        <!-- 下载次数 -->
        <div class="download-count">
          <el-icon><Download /></el-icon>
          <span>{{ formatDownloadCount(software.downloadCount) }}</span>
        </div>

        <!-- 支持的操作系统 -->
        <div class="os-support">
          <span v-for="os in parsedOsSupport" :key="os" class="os-tag">
            <el-icon>
              <component :is="getOsIcon(os)" />
            </el-icon>
            {{ getOsDisplayName(os) }}
          </span>
        </div>
      </div>

      <!-- 软件描述 -->
      <div class="software-description">
        <p :title="software.description">
          {{ truncateText(software.description, 80) }}
        </p>
      </div>

      <!-- 版本信息 -->
      <div class="version-info" v-if="software.versions && software.versions.length">
        <span class="latest-version">
          最新版本: {{ software.versions[0]?.version }}
        </span>
        <span class="version-count">
          共 {{ software.versions.length }} 个版本
        </span>
      </div>
    </div>

    <!-- 卡片底部操作 -->
    <div class="card-footer">
      <div class="action-buttons">
        <el-button
          type="primary"
          size="small"
          @click="handleSelectToggle"
          :loading="loading"
        >
          <el-icon><Plus v-if="!isSelected" /><Check v-else /></el-icon>
          {{ isSelected ? '已选择' : '选择' }}
        </el-button>

        <el-button
          type="info"
          size="small"
          @click="handleViewDetail"
          :loading="detailLoading"
        >
          <el-icon><View /></el-icon>
          详情
        </el-button>

        <el-dropdown @command="handleCommand" trigger="click">
          <el-button size="small" type="text">
            <el-icon><MoreFilled /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="download">
                <el-icon><Download /></el-icon>
                记录下载
              </el-dropdown-item>
              <el-dropdown-item command="share">
                <el-icon><Share /></el-icon>
                分享
              </el-dropdown-item>
              <el-dropdown-item command="favorite">
                <el-icon><Star /></el-icon>
                收藏
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- 快速操作标签 -->
      <div class="quick-tags" v-if="software.tags">
        <el-tag
          v-for="tag in parsedTags.slice(0, 3)"
          :key="tag"
          size="small"
          type="info"
          effect="plain"
        >
          {{ tag }}
        </el-tag>
      </div>
    </div>

    <!-- 加载遮罩 -->
    <div v-if="loading" class="loading-overlay">
      <el-icon class="is-loading"><Loading /></el-icon>
    </div>
  </div>
</template>

<script>
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Picture, Download, View, MoreFilled, Plus, Check,
  Share, Star, Loading, Monitor, Apple, Ubuntu
} from '@element-plus/icons-vue'

export default {
  name: 'EnhancedSoftwareCard',
  components: {
    Picture, Download, View, MoreFilled, Plus, Check,
    Share, Star, Loading, Monitor, Apple, Ubuntu
  },
  props: {
    software: {
      type: Object,
      required: true
    },
    selected: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['selection-change', 'view-detail', 'download', 'share', 'favorite'],
  setup(props, { emit }) {
    const detailLoading = ref(false)
    const defaultIcon = '/images/default-software-icon.png'

    // 计算属性
    const isSelected = computed(() => props.selected)
    
    const isPopular = computed(() => {
      return props.software.downloadCount > 10000 || props.software.priority > 100
    })

    const parsedOsSupport = computed(() => {
      if (!props.software.osSupport) return []
      return props.software.osSupport.split(',').map(os => os.trim().toLowerCase())
    })

    const parsedTags = computed(() => {
      if (!props.software.tags) return []
      try {
        return JSON.parse(props.software.tags)
      } catch {
        return props.software.tags.split(',').map(tag => tag.trim())
      }
    })

    // 方法
    const handleSelectionChange = (checked) => {
      emit('selection-change', props.software.id, checked)
    }

    const handleSelectToggle = () => {
      handleSelectionChange(!isSelected.value)
    }

    const handleViewDetail = async () => {
      detailLoading.value = true
      try {
        emit('view-detail', props.software.id)
      } finally {
        detailLoading.value = false
      }
    }

    const handleCommand = (command) => {
      switch (command) {
        case 'download':
          emit('download', props.software.id)
          break
        case 'share':
          emit('share', props.software)
          break
        case 'favorite':
          emit('favorite', props.software.id)
          break
      }
    }

    const formatDownloadCount = (count) => {
      if (!count) return '0'
      if (count < 1000) return count.toString()
      if (count < 1000000) return (count / 1000).toFixed(1) + 'K'
      return (count / 1000000).toFixed(1) + 'M'
    }

    const truncateText = (text, maxLength) => {
      if (!text) return ''
      return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
    }

    const getOsIcon = (os) => {
      const osLower = os.toLowerCase()
      if (osLower.includes('windows')) return Monitor
      if (osLower.includes('mac') || osLower.includes('darwin')) return Apple
      if (osLower.includes('linux') || osLower.includes('ubuntu')) return Ubuntu
      return Monitor
    }

    const getOsDisplayName = (os) => {
      const osLower = os.toLowerCase()
      if (osLower.includes('windows')) return 'Windows'
      if (osLower.includes('mac') || osLower.includes('darwin')) return 'macOS'
      if (osLower.includes('linux')) return 'Linux'
      if (osLower.includes('ubuntu')) return 'Ubuntu'
      return os
    }

    return {
      detailLoading,
      defaultIcon,
      isSelected,
      isPopular,
      parsedOsSupport,
      parsedTags,
      handleSelectionChange,
      handleSelectToggle,
      handleViewDetail,
      handleCommand,
      formatDownloadCount,
      truncateText,
      getOsIcon,
      getOsDisplayName
    }
  }
}
</script>

<style lang="scss" scoped>
.enhanced-software-card {
  position: relative;
  border: 2px solid #e4e7ed;
  border-radius: 12px;
  background: #fff;
  transition: all 0.3s ease;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;

  &:hover {
    border-color: #409eff;
    box-shadow: 0 4px 20px rgba(64, 158, 255, 0.15);
    transform: translateY(-2px);
  }

  &.selected {
    border-color: #67c23a;
    background: #f0f9ff;
    box-shadow: 0 4px 20px rgba(103, 194, 58, 0.2);
  }

  &.loading {
    pointer-events: none;
  }

  .card-header {
    position: relative;
    padding: 16px;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;

    .software-icon {
      position: relative;
      width: 48px;
      height: 48px;

      .el-image {
        width: 100%;
        height: 100%;
        border-radius: 8px;
      }

      .image-slot {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        color: #909399;
        border-radius: 8px;
      }

      .status-badges {
        position: absolute;
        top: -8px;
        right: -8px;
        display: flex;
        flex-direction: column;
        gap: 4px;
      }
    }

    .selection-box {
      margin-top: 4px;
    }
  }

  .card-body {
    padding: 0 16px;
    flex: 1;

    .software-title {
      margin-bottom: 12px;

      .name {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 6px 0;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .category-tag {
        display: inline-block;
      }
    }

    .software-meta {
      margin-bottom: 12px;
      display: flex;
      flex-direction: column;
      gap: 8px;

      .rating {
        display: flex;
        align-items: center;
        
        :deep(.el-rate) {
          height: auto;
        }
      }

      .download-count {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #606266;
        font-size: 12px;
      }

      .os-support {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;

        .os-tag {
          display: flex;
          align-items: center;
          gap: 2px;
          font-size: 11px;
          color: #909399;
          background: #f5f7fa;
          padding: 2px 6px;
          border-radius: 4px;
        }
      }
    }

    .software-description {
      margin-bottom: 12px;

      p {
        margin: 0;
        color: #606266;
        font-size: 13px;
        line-height: 1.5;
      }
    }

    .version-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      color: #909399;
      margin-bottom: 12px;

      .latest-version {
        font-weight: 500;
      }
    }
  }

  .card-footer {
    padding: 16px;
    border-top: 1px solid #f0f0f0;

    .action-buttons {
      display: flex;
      gap: 8px;
      align-items: center;
      margin-bottom: 12px;

      .el-button {
        flex: 1;

        &:last-child:not(.el-dropdown__trigger) {
          flex: none;
        }
      }
    }

    .quick-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
    }
  }

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: #409eff;
  }
}

// 响应式适配
@media (max-width: 768px) {
  .enhanced-software-card {
    .card-header {
      padding: 12px;

      .software-icon {
        width: 40px;
        height: 40px;
      }
    }

    .card-body {
      padding: 0 12px;

      .software-title .name {
        font-size: 14px;
      }
    }

    .card-footer {
      padding: 12px;

      .action-buttons {
        flex-direction: column;
        gap: 6px;

        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style>
